package xin.huangyan.accessibilityapp.internet;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import xin.huangyan.accessibilityapp.MainApplication;
import xin.huangyan.accessibilityapp.WeixinMsgManager;
import xin.huangyan.accessibilityapp.utils.HLog;

public class SocketManager {
    private static SocketManager instance;
    public static SocketManager getInstance() {
        if (instance == null) {
            synchronized (SocketManager.class){
                if (instance == null) {
                    instance = new SocketManager();
                }
            }
        }
        return instance;
    }

    ServerSocket serverSocket = null;
    private final int PORT = 9998;
    private int i = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Handler mainHandler = new Handler(Looper.getMainLooper());

    private SocketManager(){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                //输出服务器的IP地址
                try {
                    InetAddress addr = InetAddress.getLocalHost();
                    HLog.i("local host:"+addr);
                    serverSocket = new ServerSocket(PORT);
                    HLog.i("0k");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    boolean started = false;
    public void startService(){
        if (started) {
            return;
        }
        started = true;
        executor.execute(new Runnable(){
            @Override
            public void run() {
                try {
                    Socket socket = null;
                    HLog.i("waiting...");
                    //等待连接，每建立一个连接，就新建一个线程
                    while(true){
                        socket = serverSocket.accept();//等待一个客户端的连接，在连接之前，此方法是阻塞的
                        IP_ADDRESS = socket.getInetAddress().toString();
                        if (IP_ADDRESS.startsWith("/")) {
                            IP_ADDRESS = IP_ADDRESS.substring(1);
                        }
                        HLog.i("connect to "+IP_ADDRESS+":"+socket.getLocalPort());

                        new ConnectThread(socket).start();
                    }

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    HLog.i("IOException");
                    e.printStackTrace();
                }
            }
        });
    }

    //收到消息后向客户端回复信息
    class ConnectThread extends Thread{
        Socket socket = null;

        public ConnectThread(Socket socket){
            super();
            this.socket = socket;
        }

        @Override
        public void run(){
            try {
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                while(true){
                    i++;
                    String msgRecv = dis.readUTF();
                    HLog.i("msg from client:"+msgRecv);
                    handleReceiveMsg(msgRecv);
                    dos.writeUTF("" + i);
                    dos.flush();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    private void handleReceiveMsg(String msgRecv){
        if (TextUtils.isEmpty(msgRecv)) {
            return;
        }
        if ("1".equals(msgRecv)) {
            WeixinMsgManager.getInstance().sendMsg(null);
            return;
        }
        try {
            JSONObject recvObj = new JSONObject(msgRecv);
            if ("send".equals(recvObj.optString("command"))) {
                WeixinMsgManager.getInstance().sendMsg(recvObj.optString("msg"));
            }
        } catch (Exception e) {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainApplication.context, msgRecv, Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    /****************客户端*****************/

    public void sendMsg(String msg){
        new sendThread(msg).start();
    }

    private String IP_ADDRESS = "192.168.43.227";
    //新建一个子线程，向服务端发送消息
    class sendThread extends Thread {
        String message = null;

        public sendThread(String msg) {
            message = msg;
        }

        @Override
        public void run() {
            if (TextUtils.isEmpty(message)) {
                HLog.i("message is empty");
                return;
            }
            HLog.i("send message："+message);
            Socket sendSocket = null;
            DataOutputStream dos = null;
            DataInputStream dis = null;
            try {
                if ("".equals(IP_ADDRESS)) {
                    return;
                }
                sendSocket = new Socket(IP_ADDRESS, PORT);
                //获取socket的输入输出流
                dis = new DataInputStream(sendSocket.getInputStream());
                dos = new DataOutputStream(sendSocket.getOutputStream());
                dos.writeUTF(message);
                dos.flush();
                String messageRecv = dis.readUTF();//如果没有收到数据，会阻塞
                HLog.i("收到服务端回复：" + messageRecv);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (sendSocket != null) {
                        sendSocket.close();
                    }
                    if (dos != null) {
                        dos.close();
                    }
                    if (dis != null) {
                        dis.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
